package db

import (
	"fmt"
	"greatTool/models"
	"time"
)

// Stor 全局存储实例
var Stor Storage

// InitDB 初始化数据库
func InitDB(storageType string, cloudAPIURL string, cloudAPIKey string, cloudTimeout int) error {
	switch storageType {
	case "local":
		Stor = NewLocalStorage()
	case "cloud":
		if cloudAPIURL == "" || cloudAPIKey == "" {
			return fmt.Errorf("云存储需要提供API地址和密钥")
		}
		Stor = NewCloudStorage(cloudAPIURL, cloudAPIKey, cloudTimeout)
	case "sync":
		local := NewLocalStorage()
		cloud := NewCloudStorage(cloudAPIURL, cloudAPIKey, cloudTimeout)
		Stor = NewSyncStorage(local, cloud)
	default:
		return fmt.Errorf("不支持的存储类型: %s", storageType)
	}

	return Stor.Init() // 直接返回，不需要额外的 err 变量
}

// CloseDB 关闭数据库
func CloseDB() error {
	if Stor != nil {
		return Stor.Close()
	}
	return nil
}

// GetAllResources 获取所有资源
func GetAllResources() (map[models.ValJsonKey]models.ValJson, error) {
	if Stor == nil {
		return nil, fmt.Errorf("存储未初始化")
	}
	return Stor.GetAllResources()
}

// SaveResource 保存资源
func SaveResource(key models.ValJsonKey, value models.ValJson) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}
	return Stor.SaveResource(key, value)
}

// DeleteResource 删除资源
func DeleteResource(key models.ValJsonKey) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}
	return Stor.DeleteResource(key)
}

// UpdateResource 更新资源
func UpdateResource(key models.ValJsonKey, newValue models.ValJson) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}
	return Stor.UpdateResource(key, newValue)
}

// MigrateData 数据迁移工具
func MigrateData(sourceType, targetType, sourceAPIURL,
	sourceAPIKey string, sourceTimeout int, cloudAPIURL string,
	cloudAPIKey string, cloudTimeout int, debug bool) error {
	fmt.Printf("开始数据迁移: %s -> %s\n", sourceType, targetType)

	// 初始化源存储
	var sourceStorage Storage
	switch sourceType {
	case "local":
		sourceStorage = NewLocalStorage()
	case "cloud":
		if sourceAPIURL == "" || sourceAPIKey == "" {
			return fmt.Errorf("源云存储需要提供API地址和密钥")
		}
		sourceStorage = NewCloudStorage(sourceAPIURL, sourceAPIKey, sourceTimeout)
	default:
		return fmt.Errorf("不支持的源存储类型: %s", sourceType)
	}

	if err := sourceStorage.Init(); err != nil {
		return fmt.Errorf("初始化源存储失败: %w", err)
	}
	defer func(sourceStorage Storage) {
		err := sourceStorage.Close()
		if err != nil {
			// nothing .
		}
	}(sourceStorage)

	// 初始化目标存储
	var targetStorage Storage
	switch targetType {
	case "local":
		targetStorage = NewLocalStorage()
	case "cloud":
		if cloudAPIURL == "" || cloudAPIKey == "" {
			return fmt.Errorf("目标云存储需要提供API地址和密钥")
		}
		targetStorage = NewCloudStorage(cloudAPIURL, cloudAPIKey, cloudTimeout)
	default:
		return fmt.Errorf("不支持的目标存储类型: %s", targetType)
	}

	if err := targetStorage.Init(); err != nil {
		return fmt.Errorf("初始化目标存储失败: %w", err)
	}
	defer func(targetStorage Storage) {
		err := targetStorage.Close()
		if err != nil {
			// nothing .
		}
	}(targetStorage)

	// 从源存储获取数据
	fmt.Println("从源存储读取数据...")
	resources, err := sourceStorage.GetAllResources()
	if err != nil {
		return fmt.Errorf("读取源数据失败: %w", err)
	}

	fmt.Printf("找到 %d 个资源需要迁移\n", len(resources))

	// 迁移数据到目标存储
	successCount := 0
	failCount := 0

	for key, value := range resources {
		if err := targetStorage.SaveResource(key, value); err != nil {
			fmt.Printf("迁移资源失败 [%s]: %v\n", key.Key, err)
			failCount++
		} else {
			successCount++
			if debug {
				fmt.Printf("成功迁移资源: %s\n", key.Key)
			}
		}
	}

	fmt.Printf("迁移完成! 成功: %d, 失败: %d\n", successCount, failCount)

	if failCount > 0 {
		return fmt.Errorf("部分资源迁移失败")
	}

	return nil
}

// RecordAudit 记录审计
func RecordAudit(resourceKey, operation string) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}

	record := models.AuditRecord{
		ResourceKey: resourceKey,
		Operation:   operation,
		Timestamp:   time.Now().Unix(),
		Count:       1,
	}

	// 尝试使用类型断言来调用 SaveAuditRecord
	switch s := Stor.(type) {
	case interface {
		SaveAuditRecord(models.AuditRecord) error
	}:
		return s.SaveAuditRecord(record)
	default:
		return fmt.Errorf("当前存储不支持审计功能")
	}
}

// GetAuditStats 获取审计统计
func GetAuditStats() (models.AuditStats, error) {
	if Stor == nil {
		return models.AuditStats{}, fmt.Errorf("存储未初始化")
	}

	switch s := Stor.(type) {
	case interface {
		GetAuditStats() (models.AuditStats, error)
	}:
		return s.GetAuditStats()
	default:
		return models.AuditStats{}, fmt.Errorf("当前存储不支持审计功能")
	}
}

// DeleteAuditRecords 删除资源的审计记录
func DeleteAuditRecords(resourceKey string) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}

	switch s := Stor.(type) {
	case interface {
		DeleteAuditRecords(string) error
	}:
		return s.DeleteAuditRecords(resourceKey)
	default:
		return fmt.Errorf("当前存储不支持审计功能")
	}
}

// GetAllHistoryRecords 获取所有历史记录
func GetAllHistoryRecords() ([]models.HistoryRecord, error) {
	if Stor == nil {
		return nil, fmt.Errorf("存储未初始化")
	}

	switch s := Stor.(type) {
	case interface {
		GetAllHistoryRecords() ([]models.HistoryRecord, error)
	}:
		return s.GetAllHistoryRecords()
	default:
		return nil, fmt.Errorf("当前存储不支持历史记录功能")
	}
}

// DeleteHistoryRecords 删除资源的历史记录
func DeleteHistoryRecords(resourceKey string) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}

	switch s := Stor.(type) {
	case interface {
		DeleteHistoryRecords(string) error
	}:
		return s.DeleteHistoryRecords(resourceKey)
	default:
		return fmt.Errorf("当前存储不支持历史记录功能")
	}
}

func GetHistoryRecords(idx int) (models.HistoryRecord, error) {
	if Stor == nil {
		return models.HistoryRecord{}, fmt.Errorf("存储未初始化")
	}
	switch s := Stor.(type) {
	case interface {
		GetHistoryRecord(int, models.SortOrder) (models.HistoryRecord, error)
	}:
		return s.GetHistoryRecord(idx, models.Descending)
	default:
		return models.HistoryRecord{}, fmt.Errorf("当前未支持历史查询功能")
	}

}

// RecordCommandHistory 记录命令执行历史
func RecordCommandHistory(operation, resourceKey string, debug bool) error {
	if Stor == nil {
		return fmt.Errorf("存储未初始化")
	}

	// 过滤掉一些不需要记录的内部操作
	if operation == "completion" || operation == "help" || operation == "__complete" {
		return nil
	}

	record := models.HistoryRecord{
		ID:          time.Now().UnixNano(),
		ResourceKey: resourceKey,
		Operation:   operation,
		Timestamp:   time.Now().Unix(),
		TimeStr:     time.Now().Format("2006-01-02 15:04:05"),
		Command:     operation, // 新增字段，记录完整命令
	}

	switch s := Stor.(type) {
	case interface {
		SaveHistoryRecord(models.HistoryRecord) error
	}:
		return s.SaveHistoryRecord(record)
	default:
		if debug {
			fmt.Printf("当前存储不支持历史记录功能\n")
		}
		return nil
	}
}

// CleanupResourceHistory 添加一个函数来清理资源时同时清理历史记录
func CleanupResourceHistory(resourceKey string, debug bool) {
	if err := DeleteHistoryRecords(resourceKey); err != nil && debug {
		fmt.Printf("清理资源历史记录失败: %v\n", err)
	}
	if err := DeleteAuditRecords(resourceKey); err != nil && debug {
		fmt.Printf("清理资源审计记录失败: %v\n", err)
	}
}
